<template>
  <div class="product-unit-page">
    <el-card class="unit-card">
      <template #header>
        <div class="card-header">
          <span>计量单位</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增单位</el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">批量删除</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="单位名称">
            <el-input v-model="searchForm.unitName" placeholder="请输入单位名称" clearable />
          </el-form-item>
          <el-form-item label="单位编码">
            <el-input v-model="searchForm.unitCode" placeholder="请输入单位编码" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="dataList" 
        style="width: 100%" 
        @selection-change="handleSelectionChange"
        v-loading="loading">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="unitName" label="单位名称" width="150" />
        <el-table-column prop="unitCode" label="单位编码" width="120" />
        <el-table-column prop="baseUnitName" label="基本单位" width="120" />
        <el-table-column prop="conversionRatio" label="换算比例" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      @close="handleDialogClose">
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="formRef" 
        label-width="120px">
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="formData.unitName" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位编码" prop="unitCode">
          <el-input v-model="formData.unitCode" placeholder="请输入单位编码" />
        </el-form-item>
        <el-form-item label="基本单位" prop="baseUnitId">
          <el-select v-model="formData.baseUnitId" placeholder="请选择基本单位" clearable>
            <el-option 
              v-for="item in unitOptions" 
              :key="item.id" 
              :label="item.unitName" 
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="换算比例" prop="conversionRatio">
          <el-input-number 
            v-model="formData.conversionRatio" 
            :precision="4" 
            :step="0.1" 
            :min="0.0001" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="单位详情" v-model="viewDialogVisible" width="500px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="单位名称">{{ viewData.unitName }}</el-descriptions-item>
        <el-descriptions-item label="单位编码">{{ viewData.unitCode }}</el-descriptions-item>
        <el-descriptions-item label="基本单位">{{ viewData.baseUnitName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="换算比例">{{ viewData.conversionRatio }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.status === 1 ? 'success' : 'danger'">
            {{ viewData.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUnitList, 
  getUnitListPage,
  getUnitDetail, 
  addUnit, 
  updateUnit, 
  deleteUnit, 
  deleteUnits, 
  updateUnitStatus,
  getAllUnits
} from '@/api/product'

// 响应式数据
const loading = ref(false)
const dataList = ref([])
const selectedIds = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const submitLoading = ref(false)
const unitOptions = ref([])
const formRef = ref()
const viewData = ref({})

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  unitName: '',
  unitCode: '',
  status: null
})

// 表单数据
const formData = reactive({
  id: null,
  unitName: '',
  unitCode: '',
  baseUnitId: null,
  conversionRatio: 1,
  status: 1
})

// 表单验证规则
const formRules = {
  unitName: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  unitCode: [{ required: true, message: '请输入单位编码', trigger: 'blur' }],
  conversionRatio: [{ required: true, message: '请输入换算比例', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 计算属性
const dialogTitle = computed(() => formData.id ? '编辑单位' : '新增单位')

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      unitName: searchForm.unitName,
      unitCode: searchForm.unitCode,
      status: searchForm.status,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    const res = await getUnitListPage(params)
    if (res.code === 200) {
      dataList.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadUnits = async () => {
  try {
    const res = await getAllUnits()
    if (res.code === 200) {
      unitOptions.value = res.data
    } else {
      ElMessage.error(res.message || '获取单位数据失败')
    }
  } catch (error) {
    console.error('加载单位数据失败:', error)
    ElMessage.error('加载单位数据失败')
  }
}

const handleSearch = () => {
  pageNum.value = 1
  loadData()
}

const handleReset = () => {
  searchForm.unitName = ''
  searchForm.unitCode = ''
  searchForm.status = null
  pageNum.value = 1
  loadData()
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleView = async (row) => {
  try {
    const res = await getUnitDetail(row.id)
    if (res.code === 200) {
      viewData.value = res.data
      viewDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

const handleEdit = (row) => {
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个单位吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteUnit(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 如果当前页只有一条数据且不是第一页，则跳转到上一页
      if (dataList.value.length === 1 && pageNum.value > 1) {
        pageNum.value--
      }
      loadData()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个单位吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteUnits(selectedIds.value)
    if (res.code === 200) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      // 如果删除后当前页没有数据且不是第一页，则跳转到上一页
      if (dataList.value.length <= selectedIds.value.length && pageNum.value > 1) {
        pageNum.value--
      }
      loadData()
    } else {
      ElMessage.error(res.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const res = await updateUnitStatus(row.id, newStatus)
    if (res.code === 200) {
      ElMessage.success('状态更新成功')
      loadData()
    } else {
      ElMessage.error(res.message || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    const api = formData.id ? updateUnit : addUnit
    const res = await api(formData)
    
    if (res.code === 200) {
      ElMessage.success(formData.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(res.message || (formData.id ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    unitName: '',
    unitCode: '',
    baseUnitId: null,
    conversionRatio: 1,
    status: 1
  })
  formRef.value?.resetFields()
}

const handlePageChange = (newPage) => {
  pageNum.value = newPage
  loadData()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  pageNum.value = 1
  loadData()
}

// 生命周期
onMounted(() => {
  loadData()
  loadUnits()
})
</script>

<style scoped>
.product-unit-page {
  padding: 20px;
}

.unit-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
}
</style>